package com.pri.chat.activity;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.VerifyBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.GridImageAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.model.VerifyModel;
import com.pri.chat.model.VerifyMsgModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.qiniu.android.storage.UploadManager;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogLoading;
import com.vondear.rxui.view.progressing.SpriteFactory;
import com.vondear.rxui.view.progressing.Style;
import com.vondear.rxui.view.progressing.sprite.Sprite;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/23
 */
public class RealVerifyActivity extends BaseActivity {
//    @BindView(R.id.tv_verify_status)
//    TextView tvVerifyStatus;
    @BindView(R.id.paizhao)
    ImageView paizhao;
    @BindView(R.id.btn_take_photo)
    Button btn_take_photo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_real_verify_layout;
    }

    private String realPath;
    @Override
    protected void initView() {
        setTitle("真人认证");
        realPath = getIntent().getExtras().getString("realPath");
//        initImg();
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
                .fallback( R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
                .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
        Glide.with(mContext).load(realPath).apply(options).into(paizhao);
    }

    @Override
    protected void initData() {
//        SubscriberOnNextListener<BaseBean<VerifyBean>> onNextListener = baseBean -> {
//            if(baseBean.getData().getRzStatus()==1){
//                tvReg.setVisibility(View.GONE);
//                tvVerifyStatus.setText("审核成功");
//                tvVerifyStatus.setVisibility(View.VISIBLE);
//                etLoginName.setEnabled(false);
//                etLoginName.setText(baseBean.getData().getTrueName());
//                LocalMedia localMedia=new LocalMedia();
//                localMedia.setPath(baseBean.getData().getRealPic());
//                localMediaList.add(localMedia);
//                mPostAdapter.notifyDataSetChanged();
//            }
//        };
//        VerifyModel userModel = new VerifyModel();
//        userModel.setMemberId(SharedHelper.readId(this));
//        userModel.setType(1);
//        Gson gson = new Gson();
//        String s = gson.toJson(userModel);
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
//        HttpMethods.getInstance().verify(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }



    @OnClick({R.id.btn_take_photo,R.id.paizhao})
    public void onViewClicked(View v) {
        if(v.getId() == R.id.btn_take_photo){
            if(StringUtil.isEmpty(mImgPath)){
                RxToast.normal("请先拍照上传图片！");
                return;
            }
            httpVerify();
        }else if(v.getId() == R.id.paizhao){
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                    .forResult(PictureConfig.REQUEST_CAMERA);
        }
    }
    private RxDialogLoading rxDialogLoading;
    private static final String TAG = "RealVerifyActivity";
    private void initLoadingDialog() {
        rxDialogLoading = new RxDialogLoading(this);
        Sprite sprite = SpriteFactory.create(Style.THREE_BOUNCE);//设置style
        rxDialogLoading.getLoadingView().setIndeterminateDrawable(sprite);
        rxDialogLoading.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        rxDialogLoading.setCancelable(false);//设置是否可取消
        rxDialogLoading.show();
    }
    private UploadManager uploadManager = new UploadManager();
    private void uploadImg(String data) {
        initLoadingDialog();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                (key1, info, res) -> {
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK()) {
                        rxDialogLoading.dismiss();
                        mImgPath = HttpMethods.QN_PATH + key1;
                    } else {
                        Log.i("qiniu", "Upload Fail");
                    }
                    Log.i("qiniu", key1 + ",\r\n " + info + ",\r\n " + res);
                }, null);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.REQUEST_CAMERA:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    String locationPath = PictureSelector.obtainMultipleResult(data).get(0).getPath();
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        locationPath = PictureSelector.obtainMultipleResult(data).get(0).getAndroidQToPath();
                    }
                    RequestOptions options = new RequestOptions()
                            .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
                            .fallback( R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
                            .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
                    Glide.with(mContext).load(locationPath).apply(options).into(paizhao);
                    uploadImg(locationPath);
                }
                break;

        }
    }
    String mImgPath="";
    private void httpVerify() {
        SubscriberOnNextListener<BaseBean<VerifyBean>> onNextListener = baseBean -> {
            RxToast.normal("提交成功");
            finish();
        };
        VerifyMsgModel userModel = new VerifyMsgModel();
        userModel.setMemberId(SharedHelper.readId(this));
        userModel.setRealPath(mImgPath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().trueNameRengZheng(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }
}
